//
//  DolphinViewController.m
//  Dolphin
//
//  Created by Handymood on 11-6-22.
//  Copyright 2011 __Hanydmood__. All rights reserved.
//

#import "DolphinViewController.h"
#import "UIImageLayer.h"
#import "DolphinAppDelegate.h"
#import "iToast.h"

#define CVC_VIEW_TAG		999

@implementation DolphinViewController

- (void)dealloc
{
    [_socket setDelegate:nil];
    [_socket disconnect];
    [_socket release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    become_active_flag = FALSE;
    cur_id = 0;
    
    if (nil == _socket) {
        _socket = [[AsyncSocket alloc] initWithDelegate:self];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"trigger_video" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"shift_to_main_page" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"update_slideshow" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"exit_button_trigger" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:
    @"PAGE_ID" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:
    @"SHIFT_TO_PAGE" object:Nil];
    
    // 对应 = 展厅号|项目号|按钮号|命令号|值
    NSLog(@"对应 = 展厅号|项目号|按钮号|命令号|值");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:
     @"send_socket" object:Nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification 
                                               object:NULL];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) 
                                                 name:UIApplicationWillTerminateNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) 
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) 
                                                 name:UIApplicationWillEnterForegroundNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) 
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];

    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    curInterfaceOrientation = UIInterfaceOrientationPortrait;
    
    [self bookGen];
    
    UIView * tapView = [[[UIView alloc] initWithFrame:CGRectMake(900, 0, 200, 100)] autorelease];
    tapView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tapView];
    
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    tapGesture.numberOfTapsRequired = 2;
    [tapView addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    [self connectToSocket];
}

- (void) handleDoubleTap:(id)sender
{
    if (nil == _inputVC) {
        _inputVC = [[IpInputViewController alloc] initWithNibName:@"IpInputViewController" bundle:nil];
    }
    
    [_inputVC setBlock:^() {
        DolphinAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
        [[NSUserDefaults standardUserDefaults] setObject:appDelegate.ipAddress forKey:IP_ADDRESS];
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:appDelegate.port] forKey:IP_PORT];
        [UIView animateWithDuration:0.5 animations:^{
            _inputVC.view.alpha = 0;
        } completion:^(BOOL finished) {
            [self connectToSocket];
            [_inputVC.view removeFromSuperview];
        }];
    }];

    _inputVC.view.alpha = 1;
    [self.view addSubview:_inputVC.view];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
}

-(void) bookGen
{ 
    if(mediaBook)
    {
        [mediaBook reset];
        [mediaBook removeFromSuperview];
        [mediaBook release];
    }

    mediaBook = [[MediaBook alloc] init];
    
    //multiple layer demo
    [mediaBook initBook:@"default_gallery.xml" suffix:@"default" curOrientation:curInterfaceOrientation];
    [self.view addSubview:mediaBook];
    
    menu = [[MediaBook alloc] init];
    [menu initBook:@"menu.xml" suffix:@"menu" curOrientation:UIInterfaceOrientationLandscapeRight];
    menu.frame = CGRectMake(0, 675, 1024, 768);
    [self.view addSubview:menu];
    
    LayerInfo *layerInfo= [[LayerInfo alloc] init];

    layerInfo.type =  @"img";
    layerInfo.resPath = @"blank.png";
    layerInfo.x = 0;
    layerInfo.y = 0;
    layerInfo.ani = 1;
    layerInfo.aniprefix = @"guang";
    layerInfo.anistartindex = 1;
    layerInfo.discrete = 2;
    layerInfo.aniendindex = 50;
    layerInfo.anisuffix = @".png";
    layerInfo.aniduration = 1.5;
    layerInfo.anirepeat = 0;
    
    bubble = [[UIImageLayer alloc] init];
    bubble.userInteractionEnabled = FALSE;
    [bubble initImage:@"blank.png" useOriginalSize:TRUE ratioMode:0 layerInfo:layerInfo];
    bubble.frame = CGRectMake(184, 616, bubble.frame.size.width, bubble.frame.size.height);
    [self.view addSubview:bubble];
    bubble.hidden = TRUE;

}

-(void)applicationWillResignActive:(UIApplication *)UIApplicationWillResignActiveNotification
{
    //timer stop code
    
    NSLog(@"application will resign active");
    
}

- (void)applicationWillTerminate:(UIApplication *)UIApplicationWillTerminateNotification
{
    NSLog(@"application will terminate");
}

- (void)applicationDidBecomeActive:(UIApplication *)UIApplicationDidBecomeActiveNotification
{
    NSLog(@"application did become active");
}

- (void)applicationWillEnterForeground:(UIApplication *)UIApplicationWillEnterForegroundNotification
{
    NSLog(@"Application Will Enter Foreground");
}

- (void)applicationDidEnterBackground:(UIApplication *)UIApplicationDidEnterBackgroundNotification 
{
    NSLog(@"Application Did Enter Background");
    
    if (cur_id == 0) 
    {

    }
}

-(void) notificationSelector:(NSNotification *) notification
{
    NSString *curNotificationName = [notification name];
    //NSLog(@"NOTIFICATION NAME %@",curNotificationName);    

    if ([curNotificationName isEqualToString:@"update_slideshow"])
    {
        NSString *path= [[NSString alloc] initWithString:[notification object]];
        
        if(mediaBook)
        {
            [mediaBook reset];
            [mediaBook removeFromSuperview];
            [mediaBook release];
        }
        
        mediaBook = [[MediaBook alloc] init];
                
        [mediaBook initBook:path suffix:@"default" curOrientation:curInterfaceOrientation];
        [self.view addSubview:mediaBook];
    }
    else if([curNotificationName isEqualToString:@"PAGE_ID" ])
    {  
        UIImageLayer *tempBtn =  [notification object];
        cur_id = tempBtn.button_id ;
       
        [mediaBook shiftToPageId:cur_id-1];
        bubble.frame = CGRectMake(184+(cur_id-1)*92, 616, bubble.frame.size.width, bubble.frame.size.height);
    }
    else if([curNotificationName isEqualToString:@"send_socket"])
    {
        UIImageLayer *tempBtn =  [notification object];
        NSString *curData = tempBtn.value;
        
        [self connectToSocket];
        
        NSData * data = [curData dataUsingEncoding:NSUTF8StringEncoding];
        [_socket writeData:data withTimeout:-1 tag:1];
        NSLog(@"now sending socket data:%@",curData); 
    } 
}

- (void)viewDidUnload
{
    if(mediaBook)
    {
        [mediaBook reset];
        [mediaBook removeFromSuperview];
        [mediaBook release];
    }
    
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (!mediaBook) 
    {
        return FALSE;
    }
 
    if(interfaceOrientation == UIInterfaceOrientationPortrait || 
       interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        mediaBook.curOrientationView = @"v";
    }
    else
    {
        mediaBook.curOrientationView = @"h";
    }
    
    if([mediaBook.gDataSet.align isEqualToString: @"v"])
    {
        if(interfaceOrientation == UIInterfaceOrientationPortrait || 
           interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        {
            [mediaBook layoutAdjustWithOrientation:interfaceOrientation orientaionType:mediaBook.gDataSet.align];
            curInterfaceOrientation = interfaceOrientation;
            return YES;
        }
        else
        {
            return NO;
        }
    }
    else if([mediaBook.gDataSet.align isEqualToString: @"h"])
    {
        if(interfaceOrientation == UIInterfaceOrientationLandscapeRight || 
           interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        {
            [mediaBook layoutAdjustWithOrientation:interfaceOrientation orientaionType:mediaBook.gDataSet.align];
            curInterfaceOrientation = interfaceOrientation;
            return YES;
        }
        else
        {
            return NO;
        }
    }
    else if([mediaBook.gDataSet.align isEqualToString: @"g"])
    {
        [mediaBook layoutAdjustWithOrientation:interfaceOrientation orientaionType:mediaBook.gDataSet.align];
        curInterfaceOrientation = interfaceOrientation;
        return YES;
    }
    else
    {
        mediaBook.preOrientation = interfaceOrientation;
        return NO;
    }
}


- (void) connectToSocket
{
    DolphinAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
    if (appDelegate.ipAddress && appDelegate.port > 0 && !_socket.isConnected) 
    {
        NSLog(@"try connest to (%@:%d)", appDelegate.ipAddress, appDelegate.port);
        [_socket disconnect];
        NSError * err = nil;
        if (![_socket connectToHost:appDelegate.ipAddress onPort:appDelegate.port withTimeout:10 error:&err]) {
            NSLog(@"socket connect error = %@", err);
            
            NSString * msg = [NSString stringWithFormat:@"无法连接到socekt服务器（%@:%d）", appDelegate.ipAddress, appDelegate.port];
            UIAlertView * alView = [[UIAlertView alloc] initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [alView show];
            [alView release];
        } else {
            NSLog(@"socket reconnected");
        }
    }
}


#pragma mark - AsyncSocketDelegate

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    if (err.code == AsyncSocketConnectTimeoutError ) 
    {
        [[iToast makeText:@"连接到socekt服务器超时 T_T"] show];
    }
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    [[iToast makeText:@"连接成功 ^_^"] show];
}

@end
